// Client

AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")

// Include

include('shared.lua')

// Initialize

function ENT:Initialize()
	self.Entity:PhysicsInit(SOLID_VPHYSICS)
	self.Entity:SetMoveType(MOVETYPE_VPHYSICS)
	self.Entity:SetSolid(SOLID_VPHYSICS)
	self.Entity:SetUseType(ONOFF_USE)
	self.Entity:SetNetworkedInt(0, 0)
	
	self:SetEntityPressing(false)
	
	if (Wire_CreateOutputs) then
		self.Outputs = Wire_CreateOutputs(self.Entity, {"Active"})
	end
	
	if (Wire_TriggerOutput) then
		Wire_TriggerOutput(self.Entity, "Active", 0)
	end
	
	util.PrecacheSound("ambient/wind/wind_hit2.wav")
end

// Think

function ENT:Think()
	local Trace = {}
	
	Trace.start = self.Entity:GetPos()
	Trace.endpos = self.Entity:GetPos() + (self.Entity:GetUp() * self:GetEntityLength())
	Trace.filter = self.Entity

	local TR = util.TraceLine(Trace) 
 
	if (TR.Hit) then
		if (self:IsEntityPressing()) then
			if (self.Entity.Push) then
				local Ang = self.Entity:GetUp() * -self:GetEntityForce()
				
				local Phys = self.Entity:GetPhysicsObject()
				
				if (Phys) then
					Phys:ApplyForceCenter(Ang)
				end
			else
				if (TR.Entity) then
					local Ang = self.Entity:GetUp() * self:GetEntityForce()
					
					if (TR.Entity:IsPlayer()) then
						local Ang = self.Entity:GetUp() * (self:GetEntityForce() / 2)
						
						TR.Entity:SetVelocity(Ang)
					else
						local Phys = TR.Entity:GetPhysicsObject()
						
						if (Phys) then
							Phys:ApplyForceCenter(Ang)
						end
					end
				end
			end
		end
	end
	
	if (self:IsEntityPressing()) then
		if (self.Entity.Sound == 1) then
			self.Entity:EmitSound("ambient/wind/wind_hit2.wav")
		end
	end
	
	self:SetEntityLabel(self.Entity.Description)
	
	self.Entity:NextThink(CurTime() + 0.5)
end

// Numpad

local function Pressed(Player, Entity, Key, IDX)
	if !Entity:IsValid() then return end
	
	local Pressing = Entity:IsEntityPressing()
	
	if (Key) then
		if (Entity.Toggle == 0) then
			Entity:SetEntityPressing(true)
		end
	else
		if (Entity.Toggle == 1) then
			Entity:SetEntityPressing(not Pressing)
		else
			Entity:SetEntityPressing(false)
		end
	end
	
	local Number = 0
	
	if (Entity:IsEntityPressing()) then
		Number = 1
	end
	
	if (Wire_TriggerOutput) then
		Wire_TriggerOutput(Entity, "Active", Number)
	end
end

numpad.Register("Fan.Pressed", Pressed)